<template>
  <div class="user-edit-container">
    <!-- Header 区域 -->
    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <!-- 用户资料 -->
    <van-cell-group class="action-card">
      <!-- 头像部分 -->
      <van-cell title="头像" is-link center>
        <template #default>
          <van-image
            class="avatar"
            :src="$store.state.userPhoto"
            @click="imageClickFn"
          >
            <!-- <van-image class="avatar" :src="profile.photo" @click="imageClickFn"> -->
            <template v-slot:error>加载失败</template>
          </van-image>
          <!-- file 选择框 -->
          <input
            type="file"
            ref="iptFile"
            v-show="false"
            accept="image/*"
            @change="onFileChange"
          />
        </template>
      </van-cell>

      <!-- 姓名部分 -->
      <van-cell
        title="名称"
        is-link
        :value="profile.name"
        @click="isShowNameDialog = true"
      />
      <!-- 修改用户名称的对话框 -->
      <van-dialog
        v-model="isShowNameDialog"
        title="修改名称"
        show-cancel-button
        :before-close="onNameDialogBeforeClose"
      >
        <!-- 输入框 -->
        <van-field
          v-model.trim="userName"
          input-align="center"
          maxlength="7"
          placeholder="请输入名称"
          :error-message="errorMessage"
          @input="nameInputChange"
        />
      </van-dialog>

      <!-- 生日部分 -->
      <van-cell
        title="生日"
        is-link
        :value="profile.birthday"
        @click="updateBirthdayFn"
      />
      <!-- 修改时间 -->
      <van-popup
        v-model="isShowBirth"
        position="bottom"
        style="height: 50%"
        round
      >
        <!-- 日期选择控件 -->
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          title="选择出生日期"
          :min-date="minDate"
          :max-date="maxDate"
          :show-toolbar="true"
          @confirm="confirmFn"
          @cancel="isShowBirth = false"
        />
      </van-popup>
    </van-cell-group>
  </div>
</template>

<script>
import {
  getUserProfileAPI,
  patchUserPhotoAPI,
  patchUserProfileAPI
} from '@/api'
import { formatDate } from '@/utils/date'
import { mapMutations } from 'vuex'
export default {
  name: 'UserEdit',
  created () {
    this.getUserProfileFn()
  },
  methods: {
    ...mapMutations(['SET_USERPHOTO']),
    // 获取用户个人信息
    async getUserProfileFn () {
      this.profile = (await getUserProfileAPI()).data.data
    },
    // 文件选择改变 -> 修改头像
    async onFileChange (ev) {
      if (ev.target.files.length === 0) return
      const formData = new FormData()
      formData.append('photo', ev.target.files[0])
      // this.profile.photo = (await patchUserPhotoAPI(formData)).data.data.photo
      this.SET_USERPHOTO((await patchUserPhotoAPI(formData)).data.data.photo)
    },
    // 图片点击事件 -> 触发文件选择
    imageClickFn () {
      this.$refs.iptFile.click()
    },
    // 点击修改名称弹窗 取消/确认
    async onNameDialogBeforeClose (action, done) {
      if (action === 'confirm') {
        if (/^[A-Za-z0-9\u4e00-\u9fa5]{1,7}$/.test(this.userName)) {
          this.profile.name = this.userName
          await patchUserProfileAPI({ name: this.profile.name })
          done()
        } else {
          this.errorMessage = '用户名中英文和数字1-7位'
          done(false)
        }
      } else this.errorMessage = null
      this.userName = ''
      done()
    },
    // 修改名称输入框改变 -> 验证输入内容
    nameInputChange (value) {
      if (!/^[A-Za-z0-9\u4e00-\u9fa5]{1,7}$/.test(value)) {
        this.errorMessage = '用户名中英文和数字1-7位'
      } else this.errorMessage = ''
    },
    // 修改出生日期 -> 显示弹出层
    updateBirthdayFn () {
      this.isShowBirth = true
      this.currentDate = new Date(this.profile.birthday)
    },
    // 修改出生日期 -> 点击完成按钮
    async confirmFn (value) {
      this.profile.birthday = formatDate(value)
      await patchUserProfileAPI({ birthday: this.profile.birthday })
      this.isShowBirth = false
    }
  },
  data () {
    return {
      profile: {}, // 用户个人简介
      isShowNameDialog: false, // 控制修改名字弹窗显示
      userName: '', // 修改名称数据
      errorMessage: null, // 输入框错误提示信息
      minDate: new Date(1900, 0, 1), // 最小可选日期
      maxDate: new Date(), // 最大可选日期
      currentDate: null, // 当前日期
      isShowBirth: false // 控制时间选择组件显示
    }
  }
}
</script>

<style lang="less" scoped>
.user-edit-container {
  padding-top: 46px;
  /deep/ .van-field__error-message {
    text-align: center;
  }
  .avatar {
    width: 50px;
    height: 50px;
  }
}
</style>
